package network.course5Http.https;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class HttpsClientDemo {
    public String readURLByHttpsGet(String url,String charset) throws Exception{
        //发送https前的准备工作
        TrustManager [] trustManagers={new TrainX509TrustManager()};
        SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
        sslContext.init(null,trustManagers,new java.security.SecureRandom());
        SSLSocketFactory ssf=sslContext.getSocketFactory();
        String content="";
        //创建对象
        URL net=new URL(url);
        //打开连接
        HttpsURLConnection connection= (HttpsURLConnection) net.openConnection();
        //输入流
        InputStream in=null;
        connection.setSSLSocketFactory(ssf);
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(6000);
        in=connection.getInputStream();
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(in,charset));
        StringBuffer stringBuffer=new StringBuffer();
        int ch;
        while((ch=bufferedReader.read())!=-1){
            stringBuffer.append((char)ch);
        }
        bufferedReader.close();
        in.close();
        content=stringBuffer.toString();
        return content;

    }

    public static void main(String[] args) throws Exception {
       System.out.println(new HttpsClientDemo().readURLByHttpsGet("https://www.17173.com","UTF-8"));

    }
}
